package com.ruoyi.llm.service;



import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.llm.constant.RabbitMqConstants;
import com.ruoyi.llm.dao.ChatHistoryAutoMapper;
import com.ruoyi.llm.domain.po.ChatHistoryPo;
import com.ruoyi.llm.domain.po.KnowledgeInfoPo;
import com.ruoyi.llm.domain.po.ProjectInfoPo;
import com.ruoyi.llm.domain.vo.ChatHistoryVo;
import com.ruoyi.llm.domain.vo.ChatMqDataVo;
import com.ruoyi.llm.domain.vo.SendChatVo;
import com.ruoyi.llm.mapper.ChatHistoryMapper;
import com.ruoyi.llm.domain.ChatHistory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@Service
@DataSource(DataSourceType.MASTER)
public class ChatHistoryService extends ServiceImpl<ChatHistoryAutoMapper,ChatHistoryPo> {

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private KnowledgeInfoService knowledgeInfoService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisMqService redisUtils;

    public List<ChatHistoryVo> getChatHistoryList(ChatHistory chatHistoryVo){
        return  chatHistoryMapper.selectChatVo(chatHistoryVo);
    }

    public List<ChatHistoryPo> getChatDetail(String sessionId,String projectId){
        LambdaQueryWrapper<ChatHistoryPo> query=new LambdaQueryWrapper<>();
        query.eq(ChatHistoryPo::getChatSessionId,sessionId).eq(ChatHistoryPo::getProjectId,projectId).orderByDesc(ChatHistoryPo::getCreateTime).last("LIMIT 50");
        return this.list(query);

    }

    public  SendChatVo getWelcome(SendChatVo sendChat) {
        ProjectInfoPo projectInfoPo = projectInfoService.getProjectInfo(sendChat.getProjectId());
        if(projectInfoPo == null){
            sendChat.setAnswer("你好，我是智能小助手，有什么可以帮你的吗？");
        }else{
            sendChat.setAnswer(projectInfoPo.getWelcomeText());
        }
        return  sendChat;
    }

    public ChatMqDataVo getChatJsonMap(SendChatVo sendChat){
        ProjectInfoPo projectInfoPo = projectInfoService.getProjectInfo(sendChat.getProjectId());
        KnowledgeInfoPo knowledgeInfoPo = knowledgeInfoService.getOneKnowledgeByproject(sendChat.getProjectId());
        JSONObject chatJson = new JSONObject();
        chatJson.put("project_id",sendChat.getProjectId());
        chatJson.put("question",sendChat.getQuestion());
        chatJson.put("debug",false);
        chatJson.put("knowledge_id",knowledgeInfoPo.getId());
        chatJson.put("user","1");
        chatJson.put("chat_session_id",sendChat.getSessionId());
        chatJson.put("chat_seq","1");

        JSONObject ragJson = new JSONObject();
        ragJson.put("top_n_paragraph",projectInfoPo.getTopNParagraph());
        ragJson.put("query_method",projectInfoPo.getQueryMethod());
        ragJson.put("score_threshold",projectInfoPo.getScoreThreshold());
        chatJson.put("rag_component",ragJson);

        JSONObject aichatJson = new JSONObject();
        aichatJson.put("prompt_template",projectInfoPo.getPromptTemplate());
        aichatJson.put("use_model",projectInfoPo.getUseModel());
        aichatJson.put("top_n_result",projectInfoPo.getTopNResult());
        chatJson.put("ai_chat_component",aichatJson);

        ChatMqDataVo mqData = new ChatMqDataVo();
        mqData.setTaskData(chatJson);
        mqData.setTaskId(UUID.randomUUID()+"");
        mqData.setNoansertxt(projectInfoPo.getNoreplayText());
        return  mqData;

    }

    public String   sentMQ(String taskId,String noanswertxt,JSONObject json){
        String redisValue="";
        System.out.println("======JSON:"+json.toString().replaceAll("\\\\","")+"========");
        rabbitTemplate.convertAndSend(RabbitMqConstants.TOPIC_AI_EXCHANGE,RabbitMqConstants.ROUTING_KEY_CHAT, json.toString().replaceAll("\\\\","").getBytes(StandardCharsets.UTF_8));
        redisValue = redisUtils.BtrOver(taskId,15000);
        if(StringUtils.isBlank(redisValue)){
            redisValue = noanswertxt;
        }
        return  redisValue;
    }


}
